//
//  TrainController.m
//  TrainT1
//  $Id: TrainController.m 45 2010-06-13 08:18:53Z qiaolun $
//
//  Created by qiaolun on 6/4/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TrainController.h"


@implementation TrainController

- (NSArray *) tableData {
	return [[tableData retain] autorelease];
}

- (void) setTableData:(NSArray *)data {
	[tableData autorelease];
	tableData = [data retain];
}

- (NSArray *) allStations {
	return [[allStations retain] autorelease];
}

- (void) setAllStations:(NSArray *)stations {
	[allStations autorelease];
	allStations = [stations retain];
}

- (NSArray *) allTrains {
	return [[allTrains retain] autorelease];
}

- (void) setAllTrains:(NSArray *)trains {
	[allTrains autorelease];
	allTrains = [trains retain];
}

- (id) init {
	
	self = [super init];
	if(self){
		trainQuery = [[TrainQuery alloc] init];
		NSLog(@"create trainQuery instance done.");
	
		
	}
	
	return self;
}

- (IBAction) tableViewAction:(id)sender {
	int clickedRow = [table_view clickedRow];
	NSLog(@"taboe view action. at row %d", clickedRow);

	if(clickedRow >= 0){
		NSDictionary *row_info = [tableData objectAtIndex:clickedRow];
		NSString *train_id = [row_info objectForKey:@"id"];
		NSLog(@"train id %@", train_id);
		
		NSArray *trainData = [trainQuery data:train_id];
		
		[trainDetailController setTableDataDetail:trainData];
		[[trainDetailController table_view_detail] reloadData];
		[[trainDetailController train_detail_window] makeKeyAndOrderFront:sender];
		
		// [train_detail_window makeKeyAndOrderFront:sender];
	}
	
}

- (void)awakeFromNib {
	[mainWindow setDelegate:self];
	
	// init data
	[self setAllTrains:[trainQuery queryAllTrains]];
	[self setAllStations:[trainQuery queryAllStations]];
}

- (void)windowWillClose:(NSNotification *)aNotification {
	[NSApp terminate:self];
}

- (IBAction) searchFromTo:(id)sender {
	NSLog(@"hit searchFromTo %@ %@", [from stringValue], [to stringValue]);
	NSArray *train_stops = [trainQuery trainsFrom:[from stringValue] to:[to stringValue]];
	
	
	NSMutableArray *trainInfos = [NSMutableArray arrayWithCapacity:[train_stops count]];
	
	
	for(int i = 0; i < [train_stops count]; i++){
		NSString *train_id = [train_stops objectAtIndex:i];
		
		NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
		
		NSArray *trainData = [trainQuery data:train_id];
		
		// NSLog(@"%@", trainData);
		if(trainData != nil){
			
			NSDictionary *from_info = nil;
			NSDictionary *to_info = nil;
			
			//search from to
			for(int j = 0; j < [trainData count]; j++){
				NSDictionary *search_t = [trainData objectAtIndex:j];
				if([[search_t objectForKey:@"stop_name"] isEqualToString:[from stringValue]]){
					from_info = [NSDictionary dictionaryWithDictionary:search_t];
				}
				if([[search_t objectForKey:@"stop_name"] isEqualToString:[to stringValue]]){
					to_info = [NSDictionary dictionaryWithDictionary:search_t];
				}
			}
			
			
			if(from_info == nil || to_info == nil){
				continue;
			}
			
			int from_stop_num = [[from_info objectForKey:@"stop_num"] intValue];			
			int to_stop_num = [[to_info objectForKey:@"stop_num"] intValue];
			if(from_stop_num > to_stop_num){
				continue;
			}
			
			
			NSMutableDictionary *trainInfo = [NSMutableDictionary dictionaryWithCapacity:5];
			[trainInfo setObject:[from_info objectForKey:@"id"] forKey:@"id"];
			[trainInfo setObject:[from_info objectForKey:@"train_code"] forKey:@"train_code"];
			[trainInfo setObject:[from_info objectForKey:@"stop_name"] forKey:@"from_station"];
			[trainInfo setObject:[from_info objectForKey:@"time_departure"] forKey:@"time_departure"];
			[trainInfo setObject:[to_info objectForKey:@"stop_name"] forKey:@"to_station"];
			[trainInfo setObject:[to_info objectForKey:@"time_arrive"] forKey:@"time_arrive"];
			
			[trainInfos addObject:trainInfo];
		}
		
		[innerPool release];
		
	}
	
	
	[self setTableData:[NSArray arrayWithArray:trainInfos]];
	[table_view reloadData];
}

- (IBAction) searchStation:(id)sender {
	NSArray *train_stops = [trainQuery trainsAtStation:[station stringValue]];
	
	
	NSMutableArray *trainInfos = [NSMutableArray arrayWithCapacity:[train_stops count]];
	
	
	for(int i = 0; i < [train_stops count]; i++){
		NSString *train_id = [train_stops objectAtIndex:i];
		
		NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
		
		NSArray *trainData = [trainQuery data:train_id];
		
		// NSLog(@"%@", trainData);
		if(trainData != nil){
			
			NSDictionary *from_info = [trainData objectAtIndex:0];
			NSDictionary *to_info = [trainData lastObject];
			
			NSMutableDictionary *trainInfo = [NSMutableDictionary dictionaryWithCapacity:5];
			[trainInfo setObject:[from_info objectForKey:@"id"] forKey:@"id"];
			[trainInfo setObject:[from_info objectForKey:@"train_code"] forKey:@"train_code"];
			[trainInfo setObject:[from_info objectForKey:@"stop_name"] forKey:@"from_station"];
			[trainInfo setObject:[from_info objectForKey:@"time_departure"] forKey:@"time_departure"];
			[trainInfo setObject:[to_info objectForKey:@"stop_name"] forKey:@"to_station"];
			[trainInfo setObject:[to_info objectForKey:@"time_arrive"] forKey:@"time_arrive"];
			
			[trainInfos addObject:trainInfo];
			
			NSLog(@"got trainInfo %@", trainInfo);
		}
		
		[innerPool release];
	}
	
	
	[self setTableData:[NSArray arrayWithArray:trainInfos]];
	[table_view reloadData];
	
}

- (IBAction) searchTrainCode:(id)sender {
	NSString *trainId = [trainQuery trainCode:[[train_code stringValue] uppercaseString]];
	
	NSArray *trainData = [trainQuery data:trainId];
	// NSLog(@"%@", trainData);
	if(trainData != nil){
		
		NSDictionary *from_info = [trainData objectAtIndex:0];
		NSDictionary *to_info = [trainData lastObject];
		
		NSMutableDictionary *trainInfo = [NSMutableDictionary dictionaryWithCapacity:5];
		[trainInfo setObject:[from_info objectForKey:@"id"] forKey:@"id"];
		[trainInfo setObject:[from_info objectForKey:@"train_code"] forKey:@"train_code"];
		[trainInfo setObject:[from_info objectForKey:@"stop_name"] forKey:@"from_station"];
		[trainInfo setObject:[from_info objectForKey:@"time_departure"] forKey:@"time_departure"];
		[trainInfo setObject:[to_info objectForKey:@"stop_name"] forKey:@"to_station"];
		[trainInfo setObject:[to_info objectForKey:@"time_arrive"] forKey:@"time_arrive"];
		
		
		
		[self setTableData:[NSArray arrayWithObjects:trainInfo, nil]];
	} else {
		[self setTableData:[NSArray arrayWithObjects:nil]];
	}
	[table_view reloadData];
}




- (int) numberOfRowsInTableView:(NSTableView *)aTableview {
	return [tableData count];
}

- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)column row:(int)row {
	
	NSString *col_id = [column identifier];
	// NSLog(@"%@", [tableData objectAtIndex:row]);
	return [[tableData objectAtIndex:row] objectForKey:col_id];
	// return [NSString stringWithFormat:@"row: %@, col: %d", [aTableColumn identifier], rowindex];
}


// NSComboBoxDataSource Protocol
- (int) numberOfItemsInComboBox:(NSComboBox *)aComboBox {
	if(aComboBox == station || aComboBox == from || aComboBox == to){
		// NSLog(@"combobox station");
	
		// NSLog(@"combox %@", aComboBox);
		return [allStations count];

	} else {
		return 0;
	}
}

- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(int)index {
	return [allStations objectAtIndex:index];
}

- (int) comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)aString {
	
	int i;
	for(i=0; i<[allStations count]; i++){
		if([[allStations objectAtIndex:i] hasPrefix:aString]){
			return i;
		}
	}
	return NSNotFound;
}

- (NSString *) comboBox:(NSComboBox *)aComboBox completedString:(NSString *)uncompletedString {
	int i;
	for(i=0; i<[allStations count]; i++){
		if([[allStations objectAtIndex:i] hasPrefix:uncompletedString]){
			return [NSString stringWithString:[allStations objectAtIndex:i]];
		}
	}
	return [NSString stringWithString:uncompletedString];
}


- (void) dealloc {
	
	[tableData release];
	[trainQuery release];
	
	[super dealloc];
}


@end
